package com.example.index.system

import android.annotation.SuppressLint
import android.content.Context
import android.preference.PreferenceManager
import org.greenrobot.eventbus.EventBus
import java.util.*

object LocaleManager {

    var appContext: Context? = null

    private const val PrefLocalLang = "PrefLocaleLangKey"

    fun init(applicationContext: Context?) {
        if (applicationContext != null)
            appContext = applicationContext
    }

    val cnLocale: Locale
        get() = Locale("zh", "CN")

    val enLocale: Locale
        get() = Locale("en", "")


    val locale: Locale?
        get() = Locale(lang)


    private var lang: String
        get() = PreferenceManager.getDefaultSharedPreferences(appContext)
            .getString(PrefLocalLang, "zh") ?: "zh"
        @SuppressLint("ApplySharedPref")
        set(value) {
            PreferenceManager.getDefaultSharedPreferences(appContext)
                .edit()
                .putString(PrefLocalLang, value)
                .commit()
        }

    fun setLocale(context: Context, local: Locale): Boolean {

        if (lang == local.language) return false
        lang = local.language

//        val resources = context.resources
//
//        resources.configuration.setLocale(local)
//
//        context.createConfigurationContext(resources.configuration)
        return true
    }

    fun createLocaleConfiguredContext(base: Context?): Context? {

        val configuration = base?.resources?.configuration
        configuration?.setLocale(locale)
        configuration?.updateFrom(configuration)
        return base?.createConfigurationContext(configuration!!)
    }

    fun postBroadCast() {
        EventBus.getDefault().post(UpdateLocaleEvent())
    }

}